package cn.wowjoy.office.materialmanage.search;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import java.util.List;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.adapter.TagBaseAdapter;
import cn.wowjoy.office.common.customview.TagLayout;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.remote.ResultEmpty;
import cn.wowjoy.office.data.response.MaterialSearchResponse;
import cn.wowjoy.office.databinding.ActivityMaterialSearchBinding;
import cn.wowjoy.office.materialmanage.stock.MaterialStockViewModel;

@Route(path = "/materialmanage/search/materialsearch")
public class MaterialSearchActivity extends NewBaseActivity<ActivityMaterialSearchBinding,MaterialStockViewModel> implements View.OnClickListener {

    private TagBaseAdapter tagBaseAdapter;
    @Autowired
    String storageCode;
    @Autowired
    String usageCode;
    @Autowired
    List<String> slectedIds;

    private CommonDialog clearDialog;
    private MDialog waitDialog;
    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.searchResult;
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        viewModel.getStockList(true,slectedIds);
    }

    private void showDialog(){
        if (null == clearDialog)
            clearDialog = new CommonDialog.Builder()
                    .showTitle(false)
                    .setContent("确认删除全部历史记录？")
                    .setCancelBtn("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            clearDialog.dismissAllowingStateLoss();
                        }
                    })
                    .setConfirmBtn("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //请求接口
                            viewModel.cleanHistory();
                            clearDialog.dismiss();
                        }
                    })
                    .create();
        clearDialog.show(getSupportFragmentManager(),null);
    }
    @Override
    protected void onResume() {
        super.onResume();
        openBroadCast();

    }

    @Override
    protected void onStop() {
        super.onStop();
        closeBroadCast();
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        binding.searchEditText.setText(msg.toString().trim());
        viewModel.setSearchWords(msg);
        viewModel.getStockList(true,slectedIds);
    }


    private void initTag(List<String> tags){
        if (!tags.isEmpty()){
            binding.historyDelete.setVisibility(View.VISIBLE);
            binding.historyResult.setVisibility(View.VISIBLE);
            binding.noHistoryText.setVisibility(View.GONE);
            if (null == tagBaseAdapter){
                tagBaseAdapter = new TagBaseAdapter(this,tags);
                tagBaseAdapter.setStyle(R.color.high_light_text,"#ffffff","#00000000",13.33f);
                binding.historyResult.setAdapter(tagBaseAdapter);
            } else {
                tagBaseAdapter.setList(tags);
            }
            binding.historyResult.setItemClickListener(new TagLayout.TagItemClickListener() {
                @Override
                public void itemClick(int position) {
                    Toast.makeText(MaterialSearchActivity.this, tags.get(position), Toast.LENGTH_SHORT).show();
                    binding.searchEditText.setText(tags.get(position));
                    viewModel.search(tags.get(position));
                    showHistory(false);

                }
            });
        } else {
            binding.historyDelete.setVisibility(View.GONE);
            binding.historyResult.setVisibility(View.GONE);
            binding.noHistoryText.setVisibility(View.VISIBLE);
        }
    }

    private void showHistory(boolean show){
        binding.searchHistory.setVisibility( show ? View.VISIBLE : View.GONE);
        binding.searchResult.setVisibility(show ? View.GONE : View.VISIBLE);
    }
    private void initView(){
        setSupportActionBar(binding.toolbar);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.emptyView.emptyContent.setText("可搜索物资名称，规格型号，物资分类，条形码");
        binding.recyclerView.setEmptyView(binding.emptyView.getRoot());
        binding.recyclerView.setAdapter(viewModel.adapter);
        binding.recyclerView.addItemDecoration(new SimpleItemDecoration(this,SimpleItemDecoration.VERTICAL_LIST));
//        binding.recyclerView.setPullRefreshEnabled(false);
//        binding.recyclerView.setLoadMoreEnabled(false);
        binding.searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (!TextUtils.isEmpty(v.getText().toString().trim())){
                    hideSoftInput();
                    viewModel.search(v.getText().toString().trim());
                }

                return true;
            }
        });
        binding.searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                binding.delete.setVisibility(TextUtils.isEmpty(binding.searchEditText.getText())?  View.GONE : View.VISIBLE);
                showHistory(TextUtils.isEmpty(binding.searchEditText.getText()));

            }
        });
        binding.delete.setOnClickListener(this);

        binding.historyDelete.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.delete:
                binding.searchEditText.setText("");
                viewModel.setSearchWords("");
                viewModel.cleanSearchList();
                removeErrorview();
                binding.delete.setVisibility(View.GONE);
                showHistory(true);
                viewModel.getHistoryLog();
                break;
            case R.id.history_delete:
                showDialog();
                break;
        }
    }


    @Override
    public boolean onSupportNavigateUp() {
        hideSoftInput();
        onBackPressed();
        return super.onSupportNavigateUp();
    }

    private void initObsever(){
        viewModel.getHistory().observe(this, new Observer<LiveDataWrapper<List<String>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<String>> listLiveDataWrapper) {
                switch (listLiveDataWrapper.status) {
                    case LOADING:
                        break;
                    case SUCCESS:
                        initTag(listLiveDataWrapper.data);
                        break;
                    case ERROR:
                        handleException(listLiveDataWrapper.error, false);
                        break;
                }

            }
        });
        viewModel.getClean().observe(this, new Observer<LiveDataWrapper<String>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<String> resultEmptyLiveDataWrapper) {
                switch (resultEmptyLiveDataWrapper.status) {
                    case LOADING:
                        break;
                    case SUCCESS:
                        binding.historyResult.setVisibility(View.GONE);
                        binding.historyDelete.setVisibility(View.GONE);
                        binding.noHistoryText.setVisibility(View.VISIBLE);
                        break;
                    case ERROR:
                        handleException(resultEmptyLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.getStockList().observe(this, new Observer<LiveDataWrapper<List<MaterialSearchResponse>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<MaterialSearchResponse>> stockListResponseLiveDataWrapper) {
                switch (stockListResponseLiveDataWrapper.status) {
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(MaterialSearchActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        handleException(stockListResponseLiveDataWrapper.error, true);
                        break;
                }
            }
        });

    }

    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }

    }
    @Override
    protected Class<MaterialStockViewModel> getViewModel() {
        return MaterialStockViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_material_search;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        binding.setViewModel(viewModel);
        viewModel.setIds(slectedIds);
        viewModel.setStorageCode(storageCode);
        viewModel.setUsageCode(usageCode);

        initObsever();
        initView();

        viewModel.getHistoryLog();

    }



}
